#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import scrapy
import math

from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urlencode
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class GansuGannanZzPolicy(BaseTaxPolicySpider):
    name = 'gansu_gannanzz_policy'
    
    province = '甘肃省'
    city: str = "甘南藏族自治州"  # 取表格
    # county: str = ""  # 取表格
    park: str = ""  # 取表格

    @classmethod
    def update_settings(cls, settings) -> None:
        downloader_middlewares = settings.getdict("DOWNLOADER_MIDDLEWARES")
        new_settings = {
            **(cls.custom_settings or {}),
            **{
                # "DOWNLOADER_MIDDLEWARES": {
                #     # "scrapy.downloadermiddlewares.useragent.UserAgentMiddleware": None,  # 为 None 失效
                #     "scrapy.downloadermiddlewares.retry.RetryMiddleware": None,  # 为 None 失效
                #     "components.middlewares.downloadmiddlewares.public.useragent_random.RandomUserAgentMiddleware": 550,
                #     "components.middlewares.downloadmiddlewares.public.company_ip_by_api.CompanyIpByApiMiddleware": 551,
                #     "components.middlewares.downloadmiddlewares.public.error_collector.ErrorCollectorMiddleware": 552,
                #     'components.middlewares.downloadmiddlewares.private.rs_6_middlewares.Rs6RetryMiddleware': 553,
                # },
                "DOWNLOAD_TIMEOUT": 200,
                # 'CONCURRENT_REQUESTS': 1,
                "HTTPERROR_ALLOWED_CODES": [400, 404, 500, 200, 202, 502, 407],
            },
        }
        settings.setdict(new_settings or {}, priority="spider")

    def start_requests(self):
        for source, county, url in [
            ['甘南藏族自治州人民政府', "", "http://www.gnzrmzf.gov.cn/zfxxgk/zc/xzgfxwj.htm"],
            ['甘南藏族自治州人民政府', "", "http://www.gnzrmzf.gov.cn/zfxxgk/zc/zfwj/zzf.htm"],
            ['甘南藏族自治州人民政府', "", "http://www.gnzrmzf.gov.cn/zfxxgk/zc/zfwj/zzbf1.htm"],
            ['甘南藏族自治州林业和草原局', "", "http://lycy.gnzrmzf.gov.cn/zwxxgk/zc1/gfxwj.htm"],
            ['甘南藏族自治州发展和改革委员会', "", "http://fzgg.gnzrmzf.gov.cn/z_f_x_x/zc/zcwj.htm"],
            ['甘南藏族自治州科学技术局', "", "http://kjj.gnzrmzf.gov.cn/zfxxgk/zc/gnzzzzzzkjzc.htm"],
            ['甘南藏族自治州财政局', "", "http://czj.gnzrmzf.gov.cn/zfxxgk1/zc.htm"],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_list, meta={'item': item})

    def parse_list(self, response, **kwargs):
        # print(response.url)
        meta = response.meta
        prev_item = meta.get('item')
        if '系统繁忙,请稍后点击' in response.text:
            yield scrapy.Request(response.url, callback=self.parse_list, dont_filter=True,
                                 meta={'item': prev_item, 'is_next': False})
        elem_list = response.xpath(
            "//*[@class='wjk_list']//li//a[(contains(@href, 'htm') or @title) and not(starts-with(text(), '|'))]/ancestor::li[string-length(string(.))>=9] | "
            "//ul//li[contains(@class, 'clearfix')]//a[(contains(@href, 'htm') or @title) and not(starts-with(text(), '|'))]/ancestor::li[string-length(string(.))>=9] | "
            # "//*[@class='lmgglis' or @class='m-ulList' or @class='hr_ls_li']//li//a[(contains(@href, 'htm') or @title) and not(starts-with(text(), '|'))]/ancestor::li[string-length(string(.))>=9] | "
            "//*[contains(@class, 'list')]//li//a[(contains(@href, 'htm') or @title) and not(starts-with(text(), '|'))]/ancestor::li[string-length(string(.))>=9]")
        print(len(elem_list), response.url)
        for elem in elem_list:
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").re_first(r"""(.*/.*)""")
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""//span/text()""").re_first(r"\d{4}-\d{2}-\d{2}")
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.htm' not in item['source_url'] and '.shtm' not in item['source_url'] and '.jsp' not in item['source_url']:
                continue
            if '/pdf/' in item['source_url'] or '/doc/' in item['source_url']:
                continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        next_url = response.xpath("//*[@class='pagebar' or contains(@class, 'p_next')]//a[contains(text(), '下页')]/@href").get()
        # total_page = response.xpath("//span[@class='p_no']/a/text()").getall()[-1]
        print(response.url, len(elem_list), 'next_url', next_url)
        if next_url:
            meta.update({'item': prev_item})
            yield response.follow(next_url, callback=self.parse_list, meta=meta)

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        # item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath("//*[@class='fbrq']/text()").get()
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl gansu_gannanzz_policy".split())
